package com.rocketmq.demo;

import com.rocketmq.constants.MqConstants;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName EBatchTest
 * @Description 批量发送消息
 * @Author Patrick Star
 * @Date 2025/7/27 17:06
 */
public class EBatchTest {

    @Test
    public void batchProducer() throws Exception {
        // 创建一个生产者 (制定一个组名)
        DefaultMQProducer producer = new DefaultMQProducer("batch-producer-group");
        // 连接namesrv
        producer.setNamesrvAddr(MqConstants.NAMESERVER_ADDR);
        // 启动
        producer.start();
        // 批量发送消息
        List<Message> msgs = Arrays.asList(
                new Message("batchTopic", "我是一组消息的A消息".getBytes()),
                new Message("batchTopic", "我是一组消息的B消息".getBytes()),
                new Message("batchTopic", "我是一组消息的C消息".getBytes())
        );
        SendResult send = producer.send(msgs);
        System.out.println(send);
        // 关闭
        producer.shutdown();
    }


    @Test
    public void batchConsumer() throws Exception {
        // 创建一个消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("batch-consumer-group");
        // 消费者拉取消息模式
        // DefaultMQPullConsumer pullConsumer = new DefaultMQPullConsumer("test-consumer-group");
        // 连接namesrv
        consumer.setNamesrvAddr(MqConstants.NAMESERVER_ADDR);
        // 订阅主题 * 代表订阅这个主题中的所有的消息 后期会有消息过滤
        consumer.subscribe("batchTopic", "*");
        // 设置一个监听器 (一直监听 异步回调方式)
        consumer.registerMessageListener((MessageListenerConcurrently) (list, context) -> {
            // 这个就是一个消费的方法 (业务处理)
            System.out.println("我是消费者");
            System.out.println(list.get(0).toString());
            System.out.println("消息的大小" + list.size());
            System.out.println("消息内容" + new String(list.get(0).getBody()));
            System.out.println("消息消费上下文" + context);
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        consumer.start();
        System.in.read();
    }
}
